package com.chushouya.product.service.common.impl;

import com.chushouya.manager.service.admin.OssService;
import com.chushouya.product.dao.entity.BrandEntity;
import com.chushouya.product.dao.entity.CategoryBrandEntity;
import com.chushouya.product.dao.entity.ProductEntity;
import com.chushouya.product.dao.entity.ProductImageRecordEntity;
import com.chushouya.product.dao.repository.BrandRepository;
import com.chushouya.product.dao.repository.CategoryBrandRepository;
import com.chushouya.product.dao.repository.ProductRepository;
import com.chushouya.product.dao.repository.ProductImageRecordRepository;
import com.chushouya.product.dto.admin.product.query.ProductQuery;
import com.chushouya.product.service.common.ProductImageGenerateService;
import com.general.framework.core.schema.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 产品图片生成服务实现
 */
@Service
@Slf4j
public class ProductImageGenerateServiceImpl implements ProductImageGenerateService {

    @Resource
    private ProductRepository productRepository;

    @Resource
    private OssService ossService;

    @Resource
    private ProductImageRecordRepository productImageRecordRepository;

    @Resource
    private CategoryBrandRepository categoryBrandRepository;

    @Resource
    private BrandRepository brandRepository;

    private static final int IMAGE_WIDTH = 800;
    private static final int ROW_HEIGHT = 50;
    private static final int HEADER_HEIGHT = 80;
    private static final int FOOTER_HEIGHT = 60;
    private static final int PADDING = 20;

    private static final Color HEADER_COLOR = new Color(255, 204, 0);
    private static final Color ROW_EVEN_COLOR = new Color(255, 255, 255);
    private static final Color ROW_ODD_COLOR = new Color(245, 245, 245);
    private static final Color BORDER_COLOR = new Color(0, 0, 0);
    private static final Color TEXT_COLOR = new Color(0, 0, 0);
    private static final Color FOOTER_COLOR = new Color(255, 102, 102);

    @Override
    public List<ProductEntity> getProductListByCategoryAndBrand(Long categoryId, Long brandId) {
        ProductQuery query = new ProductQuery();
        query.setCategoryId(categoryId);
        query.setBrandId(brandId);
        query.setStatus(1); // 只查询上架的产品
        query.setSize(15);

        PageResult<ProductEntity> products = productRepository.selectPage(query);
        log.info("查询到产品数量: {}, categoryId: {}, brandId: {}", products.getRows().size(), categoryId, brandId);
        
        return products.getRows();
    }

    @Override
    public File generateProductListImage(List<ProductEntity> products, String title, String date) {
        if (products == null || products.isEmpty()) {
            log.warn("产品列表为空，无法生成图片");
            return null;
        }

        // 生成图片
        BufferedImage image = createProductListImage(products, title, date);
        
        // 保存图片到本地
        return saveImage(image, title, date);
    }

    private int drawHeader(Graphics2D g2d, String title, String date, int y) {
        g2d.setColor(HEADER_COLOR);
        g2d.fillRect(PADDING, y, IMAGE_WIDTH - PADDING * 2, HEADER_HEIGHT);
        
        g2d.setColor(BORDER_COLOR);
        g2d.drawRect(PADDING, y, IMAGE_WIDTH - PADDING * 2, HEADER_HEIGHT);

        // 绘制标题文字
        g2d.setColor(TEXT_COLOR);
        g2d.setFont(new Font("Microsoft YaHei", Font.BOLD, 24));
        
        String headerText = title + "(" + date + ")";
        FontMetrics fm = g2d.getFontMetrics();
        int textWidth = fm.stringWidth(headerText);
        int textX = (IMAGE_WIDTH - textWidth) / 2;
        int textY = y + (HEADER_HEIGHT + fm.getAscent()) / 2 - 5;
        
        g2d.drawString(headerText, textX, textY);

        return y + HEADER_HEIGHT;
    }

    private int drawTableHeader(Graphics2D g2d, int y) {
        g2d.setColor(Color.LIGHT_GRAY);
        g2d.fillRect(PADDING, y, IMAGE_WIDTH - PADDING * 2, ROW_HEIGHT);
        
        g2d.setColor(BORDER_COLOR);
        g2d.drawRect(PADDING, y, IMAGE_WIDTH - PADDING * 2, ROW_HEIGHT);

        g2d.setColor(TEXT_COLOR);
        g2d.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));

        // 列宽度分配: 手机型号(50%), 回收价格(30%), 外观(20%)
        int col1Width = (int) ((IMAGE_WIDTH - PADDING * 2) * 0.5);
        int col2Width = (int) ((IMAGE_WIDTH - PADDING * 2) * 0.3);
        int col3Width = (int) ((IMAGE_WIDTH - PADDING * 2) * 0.2);

        FontMetrics fm = g2d.getFontMetrics();
        int textY = y + (ROW_HEIGHT + fm.getAscent()) / 2 - 5;

        // 绘制表头文字
        drawCenteredText(g2d, "手机型号", PADDING, textY, col1Width);
        drawCenteredText(g2d, "回收价格", PADDING + col1Width, textY, col2Width);
        drawCenteredText(g2d, "外观", PADDING + col1Width + col2Width, textY, col3Width);

        // 绘制列分隔线
        g2d.drawLine(PADDING + col1Width, y, PADDING + col1Width, y + ROW_HEIGHT);
        g2d.drawLine(PADDING + col1Width + col2Width, y, PADDING + col1Width + col2Width, y + ROW_HEIGHT);

        return y + ROW_HEIGHT;
    }

    private int drawProductRows(Graphics2D g2d, List<ProductEntity> products, int y) {
        int col1Width = (int) ((IMAGE_WIDTH - PADDING * 2) * 0.5);
        int col2Width = (int) ((IMAGE_WIDTH - PADDING * 2) * 0.3);
        int col3Width = (int) ((IMAGE_WIDTH - PADDING * 2) * 0.2);

        g2d.setFont(new Font("Microsoft YaHei", Font.PLAIN, 16));
        FontMetrics fm = g2d.getFontMetrics();

        for (int i = 0; i < products.size(); i++) {
            ProductEntity product = products.get(i);
            
            // 交替行颜色
            g2d.setColor(i % 2 == 0 ? ROW_EVEN_COLOR : ROW_ODD_COLOR);
            g2d.fillRect(PADDING, y, IMAGE_WIDTH - PADDING * 2, ROW_HEIGHT);
            
            g2d.setColor(BORDER_COLOR);
            g2d.drawRect(PADDING, y, IMAGE_WIDTH - PADDING * 2, ROW_HEIGHT);

            int textY = y + (ROW_HEIGHT + fm.getAscent()) / 2 - 5;

            g2d.setColor(TEXT_COLOR);
            
            // 产品名称
            String productName = product.getProductName() != null ? product.getProductName() : "";
            drawCenteredText(g2d, productName, PADDING, textY, col1Width);
            
            // 价格
            String price = product.getMaxPrice() != null ? product.getMaxPrice().toString() : "0";
            drawCenteredText(g2d, price, PADDING + col1Width, textY, col2Width);
            
            // 外观 - 固定显示"好坏都要"
            drawCenteredText(g2d, "好坏都要", PADDING + col1Width + col2Width, textY, col3Width);

            // 绘制列分隔线
            g2d.setColor(BORDER_COLOR);
            g2d.drawLine(PADDING + col1Width, y, PADDING + col1Width, y + ROW_HEIGHT);
            g2d.drawLine(PADDING + col1Width + col2Width, y, PADDING + col1Width + col2Width, y + ROW_HEIGHT);

            y += ROW_HEIGHT;
        }

        return y;
    }

    private void drawFooter(Graphics2D g2d, int y) {
        g2d.setColor(FOOTER_COLOR);
        g2d.fillRect(PADDING, y, IMAGE_WIDTH - PADDING * 2, FOOTER_HEIGHT);
        
        g2d.setColor(BORDER_COLOR);
        g2d.drawRect(PADDING, y, IMAGE_WIDTH - PADDING * 2, FOOTER_HEIGHT);

        g2d.setColor(TEXT_COLOR);
        g2d.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));

        FontMetrics fm = g2d.getFontMetrics();
        int textY = y + (FOOTER_HEIGHT / 2 + fm.getAscent()) / 2;

        String line1 = "啥都收，更多行情价格点击主页";
        String line2 = "免费上门评估";

        int text1Width = fm.stringWidth(line1);
        int text2Width = fm.stringWidth(line2);

        g2d.drawString(line1, (IMAGE_WIDTH - text1Width) / 2, textY);
        g2d.drawString(line2, (IMAGE_WIDTH - text2Width) / 2, textY + fm.getHeight());
    }

    private void drawCenteredText(Graphics2D g2d, String text, int x, int y, int width) {
        FontMetrics fm = g2d.getFontMetrics();
        int textWidth = fm.stringWidth(text);
        int textX = x + (width - textWidth) / 2;
        g2d.drawString(text, textX, y);
    }

    private File saveImage(BufferedImage image, String title, String date) {
        try {
            // 创建输出目录
            String outputDir = System.getProperty("user.home") + File.separator + "chushouya" + File.separator + "product-images";
            File dir = new File(outputDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成文件名
            String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String fileName = title.replaceAll("[\\s\\(\\)]", "_") + "_" + date.replaceAll("[\\s月日]", "") + "_" + timestamp + ".png";
            File outputFile = new File(dir, fileName);

            ImageIO.write(image, "png", outputFile);
            log.info("图片生成成功: {}", outputFile.getAbsolutePath());
            
            return outputFile;
        } catch (IOException e) {
            log.error("保存图片失败", e);
            return null;
        }
    }

    @Override
    public String generateAndUploadProductListImage(List<ProductEntity> products, String title, String date, Long categoryId, Long brandId) {
        if (products == null || products.isEmpty()) {
            log.warn("产品列表为空，无法生成图片");
            return null;
        }

        try {
            // 生成图片
            BufferedImage image = createProductListImage(products, title, date);
            
            // 将图片转换为字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            byte[] imageBytes = baos.toByteArray();
            
            // 生成OSS文件路径 - 格式: 日期_分类ID_品牌ID_产品ID.png
            String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String timestamp = new SimpleDateFormat("HHmmss").format(new Date());
            
            // 获取第一个产品ID作为文件名的一部分
            Long firstProductId = products.get(0).getProductId();
            
            // 文件名格式: yyyyMMdd_categoryId_brandId_productId_HHmmss.png
            String fileName = String.format("%s_%s_%s_%s_%s.png", 
                dateStr, 
                categoryId != null ? categoryId : "0", 
                brandId != null ? brandId : "0", 
                firstProductId,
                timestamp);
            
            String ossFilePath = "product-images/" + dateStr + "/" + fileName;
            
            // 上传到OSS
            String ossUrl = ossService.uploadFile(imageBytes, ossFilePath, "image/png");
            log.info("图片上传OSS成功: {}, 产品数量: {}, 文件名: {}", ossUrl, products.size(), fileName);
            
            // 查询品牌图片
            String brandImage = null;
            if (brandId != null) {
                BrandEntity brand = brandRepository.selectByPrimaryKey(brandId);
                if (brand != null) {
                    brandImage = brand.getBrandImage();
                }
            }
            
            // 保存记录到数据库
            saveProductImageRecord(products, title, date, categoryId, brandId, brandImage, fileName, ossFilePath, ossUrl, 1, null);
            
            return ossUrl;
        } catch (IOException e) {
            log.error("生成或上传图片失败", e);
            return null;
        }
    }

    /**
     * 创建产品列表图片
     */
    private BufferedImage createProductListImage(List<ProductEntity> products, String title, String date) {
        int tableHeight = HEADER_HEIGHT + (products.size() + 1) * ROW_HEIGHT + FOOTER_HEIGHT;
        int imageHeight = tableHeight + PADDING * 2;

        BufferedImage image = new BufferedImage(IMAGE_WIDTH, imageHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 填充白色背景
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, IMAGE_WIDTH, imageHeight);

        int currentY = PADDING;

        // 绘制标题
        currentY = drawHeader(g2d, title, date, currentY);

        // 绘制表头
        currentY = drawTableHeader(g2d, currentY);

        // 绘制产品列表
        currentY = drawProductRows(g2d, products, currentY);

        // 绘制底部信息
        drawFooter(g2d, currentY);

        g2d.dispose();
        
        return image;
    }

    @Override
    public String generateAllBrandImagesForCategory(Long categoryId, String title) {
        if (categoryId == null) {
            log.error("分类ID不能为空");
            return "失败：分类ID不能为空";
        }

        try {
            // 查询该分类下的所有品牌
            List<CategoryBrandEntity> categoryBrands = categoryBrandRepository.selectByCategoryId(categoryId);
            
            if (categoryBrands == null || categoryBrands.isEmpty()) {
                log.warn("分类ID: {} 下没有绑定任何品牌", categoryId);
                return "失败：该分类下没有绑定任何品牌";
            }

            log.info("开始批量生成分类ID: {} 下的所有品牌产品图片，共 {} 个品牌", categoryId, categoryBrands.size());

            // 生成日期字符串
            String dateStr = new SimpleDateFormat("MM月dd日").format(new Date());
            
            // 设置默认标题
            if (title == null || title.trim().isEmpty()) {
                title = "出手鸭产品回收最新行情";
            }

            int successCount = 0;
            int failCount = 0;
            StringBuilder resultMessage = new StringBuilder();
            resultMessage.append("批量生成结果：\n");

            // 遍历每个品牌生成图片
            for (CategoryBrandEntity categoryBrand : categoryBrands) {
                Long brandId = categoryBrand.getBrandId();
                
                try {
                    // 查询该品牌下的产品列表
                    List<ProductEntity> products = getProductListByCategoryAndBrand(categoryId, brandId);
                    
                    if (products == null || products.isEmpty()) {
                        log.warn("分类ID: {}, 品牌ID: {} 下没有产品", categoryId, brandId);
                        failCount++;
                        resultMessage.append(String.format("- 品牌ID: %d - 失败（无产品）\n", brandId));
                        continue;
                    }

                    // 生成并上传图片
                    String ossUrl = generateAndUploadProductListImage(products, title, dateStr, categoryId, brandId);
                    
                    if (ossUrl != null && !ossUrl.isEmpty()) {
                        successCount++;
                        resultMessage.append(String.format("- 品牌ID: %d, 品牌名: %s - 成功（产品数: %d）\n", 
                            brandId, products.get(0).getBrandName(), products.size()));
                        log.info("品牌ID: {} 图片生成成功，URL: {}", brandId, ossUrl);
                    } else {
                        failCount++;
                        resultMessage.append(String.format("- 品牌ID: %d - 失败（上传失败）\n", brandId));
                        log.error("品牌ID: {} 图片生成失败", brandId);
                    }
                    
                } catch (Exception e) {
                    failCount++;
                    resultMessage.append(String.format("- 品牌ID: %d - 失败（异常: %s）\n", brandId, e.getMessage()));
                    log.error("品牌ID: {} 图片生成异常", brandId, e);
                }
            }

            resultMessage.append(String.format("\n总计: %d 个品牌，成功: %d，失败: %d", 
                categoryBrands.size(), successCount, failCount));
            
            log.info("批量生成完成，分类ID: {}，成功: {}，失败: {}", categoryId, successCount, failCount);
            
            return resultMessage.toString();
            
        } catch (Exception e) {
            log.error("批量生成产品图片失败，分类ID: {}", categoryId, e);
            return "失败：" + e.getMessage();
        }
    }

    /**
     * 保存产品图片生成记录到数据库
     */
    private void saveProductImageRecord(List<ProductEntity> products, String title, String date, 
                                       Long categoryId, Long brandId, String brandImage, String fileName, 
                                       String ossFilePath, String ossUrl, Integer status, String remark) {
        try {
            ProductImageRecordEntity record = new ProductImageRecordEntity();
            
            // 获取第一个产品信息
            ProductEntity firstProduct = products.get(0);
            
            record.setCategoryId(categoryId);
            record.setCategoryName(firstProduct.getCategoryName());
            record.setBrandId(brandId);
            record.setBrandName(firstProduct.getBrandName());
            record.setBrandImage(brandImage);
            record.setProductId(firstProduct.getProductId());
            record.setProductName(firstProduct.getProductName());
            record.setImageTitle(title);
            record.setFileName(fileName);
            record.setOssFilePath(ossFilePath);
            record.setOssUrl(ossUrl);
            record.setProductCount(products.size());
            record.setDateStr(date);
            record.setStatus(status);
            record.setRemark(remark);
            
            // 添加日期字段，格式：2025-11-5
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
            record.setDate(sdf.format(new Date()));
            
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            
            productImageRecordRepository.insert(record);
            log.info("产品图片生成记录保存成功, recordId: {}, fileName: {}", record.getRecordId(), fileName);
        } catch (Exception e) {
            log.error("保存产品图片生成记录失败", e);
            // 不抛出异常，避免影响主流程
        }
    }
}
